//
//  WZPWebViewController.m
//  WZPItem
//
//  Created by 王王喆平 on 16/7/11.
//  Copyright © 2016年 UI. All rights reserved.
//

#import "WZPWebViewController.h"
#import <WebKit/WebKit.h>

@interface WZPWebViewController ()
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
@property (nonatomic,weak) WKWebView * webView;

@end

@implementation WZPWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    WKWebView * webView = [[WKWebView alloc]init];
    webView.frame = CGRectMake(0, 0, WZPScreenW, WZPScreenH);
    [_containerView addSubview:webView];
    _webView = webView;
    
    // 展示网页
    NSURLRequest * request = [NSURLRequest requestWithURL:_url];
    [webView loadRequest:request];
    
    // 利用KVO 进行监听
    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
    
    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];

    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

}
// 当对象即将销毁时调用
-(void)dealloc{
    
    [_webView removeObserver:self forKeyPath:@"canGoBack"];
    [_webView removeObserver:self forKeyPath:@"canGoForward"];
    [_webView removeObserver:self forKeyPath:@"title"];
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];

}
// 当监听属性变化时调用
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    self.title = _webView.title;
    _progressView.hidden = _webView.estimatedProgress >=1;
    _progressView.progress = _webView.estimatedProgress;
    _backItem.enabled = _webView.canGoBack;
    _forwardItem.enabled = _webView.canGoForward;

}
- (IBAction)back:(id)sender {
    
    [_webView goBack];
    
}
- (IBAction)forward:(id)sender {
    
    [_webView goForward];
}
- (IBAction)refresh:(id)sender {
    
    [_webView reload];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
